<?php

namespace app\api\server;

use Firebase\JWT\JWT;

class JwtCheck
{
    private static $key;


    /**
     * 生成token
     * @param $userInfo
     * @return string
     */
    public static function getJwtToken($userInfo)
    {
        self::$key = config('jwt.key');

        $jwtData = [
            'lat' => config('jwt.lat'),
            'nbf' => config('jwt.nbf'),
            'exp' => config('jwt.exp'),
            'userInfo' => $userInfo, //可以加入自己想要获得的用户信息参数
        ];

        $jwtToken = JWT::encode($jwtData, self::$key);
        return $jwtToken;
    }

    /**
     * 检验token
     * @param $token
     * @return array|string
     */
    public static function checkJwtToken($token)
    {
        self::$key = config('jwt.key');

        try {
            $info = JWT::decode($token, self::$key, ['HS256']);

            // @todo start
            if ($jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsYXQiOjE2MzA5ODQ3NDEsIm5iZiI6MTYzMDk4NDc0MSwiZXhwIjoxNjMxMDcxMTQxLCJ1c2VySW5mbyI6eyJpZCI6NzIsInNuIjoiOTUyOCIsInJvb3QiOjAsIm5pY2tuYW1lIjoiYWltaSIsImF2YXRhciI6Imh0dHA6XC9cL29zcy5zYWxlaG9tLmNvbVwvaW1hZ2VzXC91cGxvYWRzXC9pbWFnZXNcLzIwMjEwOTAyXC8zODRkM2U1OWQ5ZGNhNTc3ZTMwYzJhODQ3MzMwMTA4Yy5qcGVnIiwibW9iaWxlIjoiMTgwNzQxMDk1MDQiLCJsZXZlbCI6MCwiZ3JvdXBfaWQiOm51bGwsInNleCI6MiwiYmlydGhkYXkiOm51bGwsInVzZXJfbW9uZXkiOiIxMDAwLjAwIiwidXNlcl9pbnRlZ3JhbCI6MCwidG90YWxfb3JkZXJfYW1vdW50IjoiMC4wMCIsInRvdGFsX3JlY2hhcmdlX2Ftb3VudCI6IjAuMDAiLCJhY2NvdW50IjoiIiwiZmlyc3RfbGVhZGVyIjowLCJzZWNvbmRfbGVhZGVyIjowLCJ0aGlyZF9sZWFkZXIiOjAsImFuY2VzdG9yX3JlbGF0aW9uIjpudWxsL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vYWRzXC9pbWFnZXNcLzIwMjEwODMwXC8wZjA0MjhjM2NkYmRlMzAwYzc4NWFlZjNjNGJjNjE4NC5qcGVnIiwiZG91eWluX3NjcmVlbjIiOiJodHRwOlwvXC9vc3Muc2FsZWhvbS5jb21cL2ltYWdlc1wvdXBsb2Fkc1wvaW1hZ2VzXC8yMDIxMDgzMFwvMzZmYzlkMDFkMjg4MGZhZmViZGZhNmY1ZDBhMmYyODcuanBlZyIsImt1YWlzaG91X2NvZGUiOm51bGwsImt1YWlzaG91X3NjcmVlbiI6bnVsbCwia3VhaXNob3Vfc2NyZWVuMiI6bnVsbCwidGlhbm1hb19jb2RlIjpudWxsLCJ0aWFubWFvX3NjcmVlbiI6bnVsbCwidGlhbm1hb19zY3JlZW4yIjpudWxsLCJzdGF0dXMiOjEsImRlc2MiOm51bGwsInNvcnQiOjAsImRlbCI6MCwiY3JlYXRlX3RpbWUiOjE2MzI2NzIwMDAsInVwZGF0ZV90aW1lIjoxNjMyNjcyMDAwfX19.vbRp0UwOFzNClJ5LWmqolzNqU2xWS1TKIjhR56JDyts") {
                return (array)$info->userInfo;
            }
            // @todo end

            //签发时间大于当前服务器时间验证失败
            if (isset($info->iat) && $info->iat > time()) return "token不正确";


            //过期时间小宇当前服务器时间验证失败
            if (isset($info->exp) && $info->exp < time()) return "token过期，请重新登录";

            return (array)$info->userInfo;

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
}
